package particles;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.geom.Point;

import Movable;

/**
 * ...
 * @author 
 */

class Emitter extends Movable
{
	var mCanvas: BitmapData;
	
	var particles: Array<Particle>;
	
	var xradius: Float;
	var yradius: Float;
	
	var mCount: Int;

	var c1: UInt;
	var c2: UInt;
	
	var dx1: Float;
	var dx2: Float;
	var dy1: Float;
	var dy2: Float;

	var gx1: Float;
	var gx2: Float;
	var gy1: Float;
	var gy2: Float;

	var s1: Float;
	var s2: Float;
	
	var trail: Int;
	
	
	public function new(layer: EffectsLayer, pos: Point, ?xr: Float, ?yr: Float) 
	{
		super(pos);
		
		mCanvas = layer.canvas;

		particles = new Array<Particle>();
		
		xradius = xr != null ? xr : 10;
		yradius = yr != null ? yr : 10;
		
		mCount = 10;
		
		c1 = 0xffffff | 0xff000000;
		c2 = 0xffffff | 0xff000000;
	}
	
	
	public function SetPartCount(count: Int)
	{
		mCount = count;
	}
	
	
	public function SetPartDeltaX(min: Float, max: Float)
	{
		dx1 = min;
		dx2 = max;
	}

	
	public function SetPartDeltaY(min: Float, max: Float)
	{
		dy1 = min;
		dy2 = max;
	}
	
	
	public function SetPartGravityX(min: Float, max: Float)
	{
		gx1 = min;
		gx2 = max;
	}

	
	public function SetPartGravityY(min: Float, max: Float)
	{
		gy1 = min;
		gy2 = max;
	}

	
	public function SetPartSize(min: Float, max: Float)
	{
		s1 = min;
		s2 = max;
	}
	
	
	public function SetPartTrailing(trails: Int)
	{
		trail = trails;
	}
	
	
	public function SetPartColors(start: UInt, end: UInt)
	{
		c1 = start;
		c2 = end;
	}

	
	override function Draw()
	{
		for (p in particles) {
			p.Draw(x, y, mCanvas);
		}
	}
	
	
	private function CreateParticle(p: Particle)
	{
		p.lifeTime = GetLifeTime();
		p.maxLifeTime = p.lifeTime;
		
		p.x = Math.random() * xradius * 2;
		p.y = Math.random() * yradius * 2;
		
		p.dx = Math.random() * (dx2 - dx1) + dx1;
		p.dy = Math.random() * (dy2 - dy1) + dy1;

		p.dgx = Math.random() * (gx2 - gx1) + gx1;
		p.dgy = Math.random() * (gy2 - gy1) + gy1;
		
		p.radius = Math.random() * (s2 - s1) + s1;
				
		p.alpha = 1;
		
		p.da = -(p.alpha / p.lifeTime);
		
		p.SetColors(c1, c2);
		
		p.trail = trail;
	}
	
	
	override function Update(framesAfterUpdate: Int, framesBetweenUpdates: Int): Bool
	{
		var result = super.Update(framesAfterUpdate, framesBetweenUpdates);
		if (!result)
			return false;	// R.I.P.
				
		var i: Int = 0;
		for (p in particles) {
			i++;			
			if (--p.lifeTime <= 0) {
				if (i < mCount) {
					CreateParticle(p);
				} else {
					particles.remove(p);
					p = null;
				}
			} else {
				p.Update();
			}
		}	
		
		while (particles.length < mCount)
		{
			var p = new Particle();
			CreateParticle(p);
			particles.push(p);
		}
		
		return true;
	}
}